package com.lss.studydemo;

import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    private TemperatureMonitor temperatureMonitor;
    private TextView temperatureText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        temperatureMonitor = new TemperatureMonitor();
        temperatureMonitor.addTemperatureListener(new TemperatureAlarm());
        temperatureMonitor.addTemperatureListener(new FanController());
        // 加温按钮
        temperatureText = findViewById(R.id.temperatureTextView);
        findViewById(R.id.increaseButton).setOnClickListener(v -> {
            float temp = temperatureMonitor.currentTemperature+ 1;
            temperatureMonitor.updateTemperature(temp);
            temperatureText.setText(String.format("当前温度: %.1f°C", temp));
        });

        // 降温按钮
        findViewById(R.id.decreaseButton).setOnClickListener(v -> {
            float temp = temperatureMonitor.currentTemperature - 1;
            temperatureMonitor.updateTemperature(temp);
            temperatureText.setText(String.format("当前温度: %.1f°C", temp));
        });

        // 设置阈值按钮
        findViewById(R.id.setThresholdButton).setOnClickListener(v -> {
            EditText input = new EditText(this);
            new AlertDialog.Builder(this)
                    .setTitle("设置温度阈值")
                    .setView(input)
                    .setPositiveButton("确定", (dialog, which) -> {
                        try {
                            float threshold = Float.parseFloat(input.getText().toString());
                            temperatureMonitor.setTargetThreshold(threshold);
                        } catch (NumberFormatException e) {
                            Toast.makeText(this, "请输入有效数字", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .show();
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除所有监听器，避免内存泄漏
        temperatureMonitor.clearTemperatureListeners();
    }
}